package org.utahgtug.site.service;

import com.google.gdata.client.GoogleService;
import com.google.gdata.client.blogger.BloggerService;
import com.google.gdata.data.Feed;
import com.google.gdata.data.Entry;
import com.google.gdata.data.HtmlTextConstruct;
import com.google.gdata.util.ServiceException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.utahgtug.site.model.BlogPost;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

/**
 * User: danlangford
 * Date: 12/28/11
 */

@Service
public class BlogPostService {

	@Autowired private BloggerService bloggerService;

	private static final String BLOGID = "726118186270096432";

	public List<BlogPost> getAllPosts() {
		URL feedUrl = null;
		Feed resultFeed = null;
		try {
			feedUrl = new URL("http://www.blogger.com/feeds/" + BLOGID + "/posts/default");
			resultFeed = bloggerService.getFeed(feedUrl, Feed.class);
		} catch (ServiceException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		//return resultFeed.getEntries();
		List<BlogPost> posts = convertEntries(resultFeed.getEntries());
		return posts;
	}

	private static BlogPost convertEntry(Entry entry) {
		BlogPost post = new BlogPost();
		post.setTitle(entry.getTitle().getPlainText());
		post.setContent(((HtmlTextConstruct)entry.getTextContent().getContent()).getHtml());
//		post.setContent(((HtmlTextConstruct)entry.getTextContent().getContent()).getHtml().replaceAll("style=", "blogstyle=")); //hack to remove styles from blog
		post.setLink(entry.getLink("alternate","text/html").getHref());
		return post;
	}

	private static List<BlogPost> convertEntries(List<Entry> entries) {
		List<BlogPost> posts = new ArrayList<BlogPost>();
		for(Entry e : entries) {
			posts.add(convertEntry(e));
		}
		return posts;
	}

}
